#!/bin/bash

[ ! $(id -u) -eq 0 ] && {
	echo "please run this script with root"
	exit 1
}

exec 3>&1

#函数库名称赋值
FUNCTIONS_NAME="1_pub_funtions_makai"
for i in $FUNCTIONS_NAME ; do
        #获取库文件路径
        FUNCTIONS_URL="$(find / -path /proc -prune -o -name ${i} -print)"
        #获取不到库文件则报错并退出
        ${FUNCTIONS_URL:? Not Found}
        #加载库文件
        . $FUNCTIONS_URL
done

#限制变量取值范围
DEBUG="1"
STEP_THROUGH="1"
if [ $# -gt 0 ] ; then
        case "$1" in
                0|1|2)
                        DEBUG="$1" ;;
        esac
        case "$2" in
                1|2)
                        STEP_THROUGH="$2" ;;
        esac
fi

##DEBUG
# DEBUG=0 关闭调试
# DEBUG=1 开启调试 (默认)
#       STEP_THROUGH=1 遇到错误时暂停 (默认)
#       STEP_THROUGH=2 不管是否有错误都暂停
# DEBUG=2 遇到错误就退出
alert() {
        local RET_CODE=$?
        if [ -z "$DEBUG" ] || [ "$DEBUG" -eq 0 ] ; then
                return
        fi

        if [ "$RET_CODE" -ne 0 ] ; then
                echo " Warning: $* " >&3
                [ "$DEBUG" -eq 2 ] && exit "$RET_CODE"
                [ "$STEP_THROUGH" = 1 ] && {
                        echo "Press [Enter] to containue" >&3; read x
                }
        fi

        [ "$STEP_THROUGH" = 2 ] && {
                echo "Press [Enter] to continue" >&3; read x
        }
}

	INIT_HOSTNAME="serv1"
	INIT_NIC_NAME="eth0"
	NETWORK_URL="/etc/sysconfig/network-scripts"

	clear
        echo "for centos.7..."
        echo "This is ${ostype}"
        echo "start init ${ostype}..."

        #install software
        [ -x /usr/bin/yum ] && {
                yum clean all
		yum repolist >&3
                for i in bash-completion vim ; do
                        yum install -y $i
                        alert "$i install failed"
                done
        }

	[ $(hostname) = 'localhost' ] && { hostnamectl set-hostname ${INIT_HOSTNAME} }

	#network config
	[ -d "${NETWORK_URL}" ] && \
	[ -f "${NETWORK_URL}/ifcfg-${INIT_NIC_NAME}" ] && {
		sed -n '/ONBOOT=yes/p' ${NETWORK_URL}/ifcfg-${INIT_NIC_NAME}
		sed -i 's/BOOTPROTO=.*/BOOTPROTO=static/' ${NETWORK_URL}/ifcfg-${INIT_NIC_NAME}
		cat >${NETWORK_URL}/ifcfg-${INIT_NIC_NAME} <-EOF
			IPADDR=192.168.0.160
			NETMASK=255.255.255.0
			GATEWAY=192.168.0.1
			DNS1=218.2.135.1
		EOF
	}
